package cn.jzx.hdfs;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class WriteDemo {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("运行时传递两个参数,源文件地址 目标地址");
            return;
        }
        String srcPath = args[0];
        String destPath = args[1];
        System.out.println(srcPath);
        System.out.println(destPath);
        Configuration conf = new Configuration();
        try (FileSystem fileSystem = FileSystem.get(conf)) {
            Path dest = new Path(destPath);
            if (fileSystem.exists(dest)) {
                fileSystem.delete(dest, true);
            }
            try (FSDataOutputStream fsDataOutputStream = fileSystem.create(dest)) {
                try (InputStream inputStream = new FileInputStream(srcPath)) {
                    int size = 1024 * 1024;
                    byte[] buffer = new byte[size];
                    int n = 0;
                    while (true) {
                        if ((n = inputStream.read(buffer)) < size) {
                            if (n==-1)
                                break;
                            System.out.println(n);
                            fsDataOutputStream.write(buffer, 0, n);
                            fsDataOutputStream.hflush();
                            break;
                        }
                        System.out.println(n);
                        fsDataOutputStream.write(buffer);
                        fsDataOutputStream.hflush();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
